package com.example.lib_common.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import com.example.lib_common.base.internal.InternalBaseFragment

open class BaseMvvmFragment<VB : ViewDataBinding, VM : BaseViewModel>(private val factory: ViewModelProvider.Factory? = null) :
    InternalBaseFragment() {
    val mBinding: VB by lazy(mode = LazyThreadSafetyMode.NONE) {
        getViewBinding(layoutInflater)
    }
    val mViewModel: VM by lazy(mode = LazyThreadSafetyMode.NONE) {
        createViewModel(factory)
    }

    private var permissionCallback: ((Map<String, Boolean>) -> Unit)? = null
    private val permissionLauncher =
        registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { result ->
            permissionCallback?.invoke(result)
        }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?,
    ): View? {
        // 绑定生命周期管理
        mBinding.lifecycleOwner = this
        return mBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        beforeOnCreate(view, savedInstanceState)
        super.onViewCreated(view, savedInstanceState)
        afterOnCreate(view, savedInstanceState)
        initView()
        initListener()
        initObserver()
    }

    open fun beforeOnCreate(view: View, savedInstanceState: Bundle?) {
    }

    open fun afterOnCreate(view: View, savedInstanceState: Bundle?) {}

    open fun initView() {

    }

    open fun initListener() {

    }

    open fun initObserver() {

    }

    /** 请求权限（单个或多个都用这个方法） */
    fun requestPers(permissions: List<String>, callback: (Map<String, Boolean>) -> Unit) {
        permissionCallback = callback
        permissionLauncher.launch(permissions.toTypedArray())
    }

    /** 单个权限快捷方法 */
    fun requestPer(permission: String, callback: (Boolean) -> Unit) {
        requestPers(listOf(permission)) { result ->
            callback(result[permission] ?: false)
        }
    }

    fun isPermissionDeniedForever(permission: String): Boolean {
        // 当 shouldShowRequestPermissionRationale 返回 false 且权限未授予时
        return requireContext().checkSelfPermission(permission) != android.content.pm.PackageManager.PERMISSION_GRANTED && !shouldShowRequestPermissionRationale(
            permission
        )
    }
}